# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/6/18

library(optparse)
library(ropls)
library(magrittr)
library(tidyverse)


createWhenNoExist <- function(f) {
  !dir.exists(f) && dir.create(f)
}

option_list <- list(
  make_option("--i", default = "", type = "character", help = "metabolite data file"),
  make_option("--g", default = "", type = "character", help = "sample group file"),
  make_option("--sc", default = "sample_color.txt", type = "character", help = "sample color file"),
  make_option("--cc", default = "../calculate_config.txt", type = "character", help = "config file")
)
opt <- parse_args(OptionParser(option_list = option_list))

args <- commandArgs(trailingOnly = F)
scriptPath <- dirname(sub("--file=", "", args[grep("--file", args)]))
source(str_c(scriptPath, "/base.R"))

calculateConfigData <- read_tsv(opt$cc, col_names = F, col_types = "cc") %>%
  set_colnames(c("arg", "value"))
calculateConfigData

scaleMethod <- configGet(calculateConfigData, "scaleMethod")

sampleInfo <- read_csv(opt$g) %>%
  rename(ClassNote = Group) %>%
  select(c("SampleID", "ClassNote"))

data <- read_csv(opt$i) %>%
  rename(Metabolite = 1) %>%
  gather("Sample", "Value", -Metabolite) %>%
  spread(Metabolite, "Value") %>%
  filter(Sample %in% sampleInfo$SampleID)

numColumns <- colnames(data) %>%
  keep(function(x) {
    startsWith(x, "Nubmer") || startsWith(x, "Number")
  })

data <- data %>%
  mutate_at(vars(numColumns), as.numeric) %>%
  mutate_at(vars(-numColumns), factor) %>%
  column_to_rownames("Sample") %>%
  mutate_all(as.numeric) %>%
  as.data.frame()

print(str(data))

parent <- "./"
createWhenNoExist(parent)
crossValI <- min(nrow(data), 7)

scaleC <- if (scaleMethod == "scale") "standard" else scaleMethod
pcaRs <- opls(data, plotL = F, crossvalI = crossValI, scaleC = scaleC)
df <- pcaRs@modelDF %>%
  as_tibble()
if (nrow(df) < 3) {
  pcaRs <- opls(data, plotL = F, crossvalI = crossValI, predI = 3, scaleC = scaleC)
}

pcaRs@modelDF

parameterData <- pcaRs@modelDF %>%
  select(c(1:2)) %>%
  set_colnames(c("R2", "Cumulative R2")) %>%
  mutate(pcName = paste0("PC", 1:n())) %>%
  filter(pcName %in% str_c("PC", 1:5)) %>%
  remove_rownames() %>%
  column_to_rownames("pcName") %>%
  t()

print("=in=")
print(parameterData)

write.csv(parameterData, paste0(parent, "/PCA_R2.csv"), quote = FALSE)

pcData <- pcaRs@scoreMN %>%
  as.data.frame() %>%
  rownames_to_column("SampleID") %>%
  select("SampleID", num_range("p", 1:5)) %>%
  rename_at(vars(-c("SampleID")), function(x) {
    str_replace(x, "p", "PC")
  }) %>%
  column_to_rownames("SampleID")

write.csv(pcData, paste0(parent, "/PCA_Score.csv"), quote = FALSE)
